package com.shawn.springboot.integeration.netty.future;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangjian
 * @title: SyncWriteCache
 * @projectName 12-springboot学习
 * @description: 同步写入缓存
 * @date 2021/4/2713:52
 */
@Slf4j
public class SyncWriteCache {
    public static final Cache<String, SyncWriteFuture> FUTURE_CACHE =
            CacheBuilder.newBuilder()
            // 设置缓存保存元素上限,超过上限采用LRU淘汰
            .maximumSize(65535)
            // 设置缓存内元素30秒没有读写,则过期
            .expireAfterAccess(30, TimeUnit.SECONDS)
            // 设置缓存移除监听器,打印日志
            .removalListener((RemovalListener<String, SyncWriteFuture>) notification ->
                    log.debug("移除缓存[{}][{}][{}]",notification.getKey(),
                    notification.getValue(),notification.getCause()))
            .build();
    public static void put(String key,SyncWriteFuture future) {FUTURE_CACHE.put(key,future);}

    public static SyncWriteFuture get(String key) {
       return FUTURE_CACHE.getIfPresent(key);
    }
    public static void clear(String key) {
        FUTURE_CACHE.invalidate(key);
    }
}
